import requests
import random
import json
from lxml import etree
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse


def __UA__():
    user_agents = [
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 '
        'Safari/537.36 OPR/26.0.1656.60',
        'Opera/8.0 (Windows NT 5.1; U; en)',
        'Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50',
        'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.50',
        'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0',
        'Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) '
        'Firefox/3.6.10',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2 ',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',
        'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
        'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 '
        'Safari/537.36',
        'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER',
        'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)',
        'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0',
        'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0) ',
    ]
    user_agent = random.choice(user_agents)  # random.choice(),从列表中随机抽取一个对象
    return user_agent


class AiTinSpider:
    def __init__(self):
        self.Domain = "http://www.2t58.com"
        self.headres = {
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            # 'Cookie': 'Hm_lvt_b8f2e33447143b75e7e4463e224d6b7f=1712137402; 626298=43.22743; Hm_lpvt_b8f2e33447143b75e7e4463e224d6b7f=1712143248',
            'Origin': 'http://www.2t58.com',
            'Pragma': 'no-cache',
            'Referer': 'http://www.2t58.com/song/bnZka25rbWQ.html',
            # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
            "User-Agent": __UA__(),
            'X-Requested-With': 'XMLHttpRequest',
        }
    
    # 搜索音乐
    def SearchMusic(self, MusicName):
        url = "http://www.2t58.com/so/%s.html" % MusicName
        res = requests.get(url, headers=self.headres).text
        response = etree.HTML(res)
        MusicList = []
        # 获取音乐列表
        for obj in response.xpath("/html/body/div[1]/div/div[2]/ul/li"):
            MusicAthorInfo = str(obj.xpath('./div[1]/a/text()')[0]).replace("\xa0", "").replace("&", '')
            # 音乐歌手
            MusicAthor = MusicAthorInfo.split("-")[0]
            # 音乐名称
            SMusicName = MusicAthorInfo.split("-")[1]
            MusicHref = str(obj.xpath('./div[1]/a/@href')[0]).replace("/song/", '').replace('.html', '')
            # 判断是否有 MV,如果没有则返回空字典，反正返回字典
            isMV = obj.xpath("./div[2]/a/@href")
            if len(isMV) > 0:
                isMV = str(isMV[0]).replace("/video/", '').replace('.html', '')
                pass
            else:
                isMV = ""
            
            MusicData = {
                "MusicAthor": MusicAthor,
                "MusicName": SMusicName,
                "MusicId": MusicHref,
                "MVId": isMV
            }
            
            MusicList.append(MusicData)
        
        # 获取分页
        PageList = []
        PageXpath = response.xpath('/html/body/div[1]/div/div[2]/div[2]/a')
        PageDict = {
            "current": None,
            "Length": None
        }
        for obj in range(len(PageXpath)):
            className = PageXpath[obj].xpath("./@class")
            if len(className) > 0:
                PageDict['current'] = PageXpath[obj].xpath('./text()')[0]
            elif obj == len(PageXpath) - 1:
                PageDict['Length'] = str(PageXpath[obj].xpath('./@href')[0]).split(".html")[0][-1]
        
        Result = {
            "MusicList": MusicList,
            "PageObjects": PageDict
        }
        return Result
    
    # 获取音乐源
    def GetMusicData(self, MusicId):
        url = "http://www.2t58.com/js/play.php"
        data = {
            "id": MusicId,
            "type": "music"
        }
        try:
            response = requests.post(url, headers=self.headres, data=data)
            return response.json()
        except Exception as e:
            return {}
    
    # 获取mv源
    def GetMusicMVData(self, MusicMVId):
        url = "http://www.2t58.com/plug/down.php?ac=vplay&id=%s&q=3000" % MusicMVId
        
        return url


sp = AiTinSpider()


# 搜索音乐 api
def Api_Search(request):
    if request.method == 'POST':
        MusicName = request.POST.get('MusicName')
        if MusicName is None or len(MusicName) == 0:
            return HttpResponse("请搜索搜索内容", status=400)
        Response = sp.SearchMusic(MusicName=MusicName)
        return HttpResponse(json.dumps(Response), status=200, content_type="application/json")
    else:
        return HttpResponse("不支持此请求方法", status=400)


# 获取音乐源api
def Api_GetMusicInfo(request):
    if request.method == 'POST':
        MusicID = request.POST.get('MusicId')
        response = sp.GetMusicData(MusicId=MusicID)
        return HttpResponse(json.dumps(response), status=200, content_type="application/json")
    else:
        return HttpResponse("不支持此请求方法", status=400)


# 获取mv源
def Api_GetMusicMv(request):
    if request.method == 'POST':
        MusicMVId = request.POST.get('MusicMVId')
        response = sp.GetMusicMVData(MusicMVId=MusicMVId)
        return HttpResponse(json.dumps(response), status=200, content_type="application/json")
    else:
        return HttpResponse("不支持此请求方法", status=400)
